package com.horton;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class SignTaskMain {

    //https://stock.xueqiu.com/v5/stock/realtime/pankou.json?symbol=SH603369
    public static String urlPrefix = "https://stock.xueqiu.com/v5/stock/realtime/pankou.json?symbol="; //股票
    //https://fund.xueqiu.com/dj/open/fund/growth/161725?day=30
    public static String urlPrefixFund = "https://fund.xueqiu.com/dj/open/fund/growth/"; //基金
    public static String urlSuffixFund = "?day=30"; //基金
    public static String pushPostUrl = "http://www.pushplus.plus/send";
    public static String topic = "";
    public static String token = "";
    public static List<JsonRespVO> list = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        new SignTaskMain().initJsonConfig();
        if (token.isEmpty() || topic.isEmpty()) {
            return;
        }
        buildPushContent();
        buildPushContentFund();
        String jsonString = JSON.toJSONString(list, SerializerFeature.PrettyFormat);
        System.out.println(jsonString);
        if (list.size() > 0) {
            doPost(pushPostUrl, jsonString);
        }
    }

    //读取json配置文件
    private void initJsonConfig() throws IOException {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("userConfig.json");
        assert is != null;
        String string = IOUtils.toString(is, StandardCharsets.UTF_8);
        JSONObject jsonObject = JSONObject.parseObject(string);
        token = jsonObject.getString("token");
        topic = jsonObject.getString("topic");
    }

    public static void buildPushContent() throws IOException {
        StockEnum[] stockEnums = StockEnum.values();
        for (StockEnum stockEnum : stockEnums) {
            CloseableHttpResponse httpResponse = doGet(urlPrefix + stockEnum.stockCode);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String entityStr = EntityUtils.toString(httpResponse.getEntity());
                JSONObject jsonObject = JSONObject.parseObject(entityStr);
                String current = jsonObject.getJSONObject("data").getString("current");
                if (Double.parseDouble(current) <= stockEnum.targetPrice) {
                    JsonRespVO jsonRespVO = new JsonRespVO.Builder()
                            .name(stockEnum.stockName)
                            .label(stockEnum.label)
                            .price(current)
                            .targetPrice(stockEnum.targetPrice.toString())
                            .alarm("小于等于目标值，触发警报！")
                            .build();
                    list.add(jsonRespVO);
                }
            }
            httpResponse.close();
        }
    }

    public static void buildPushContentFund() throws IOException {
        FundEnum[] fundEnums = FundEnum.values();
        for (FundEnum fundEnum : fundEnums) {
            String urlMid = fundEnum.fundCode.replaceAll("F", "");
            CloseableHttpResponse httpResponse = doGet(urlPrefixFund + urlMid + urlSuffixFund);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String entityStr = EntityUtils.toString(httpResponse.getEntity());
                JSONObject jsonObject = JSONObject.parseObject(entityStr);
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("fund_nav_growth");
                JSONObject object = jsonArray.getJSONObject(jsonArray.size() - 1);
                String date = object.getString("date");
                String nav = object.getString("nav");
                String percentage = object.getString("percentage");
                JsonRespVO jsonRespVO = new JsonRespVO.Builder()
                        .name(fundEnum.fundName)
                        .label(fundEnum.label)
                        .price(nav)
                        .targetPrice(fundEnum.targetPrice.toString())
                        .date(date)
                        .percentage(percentage + "%")
                        .build();
                list.add(jsonRespVO);
            }
            httpResponse.close();
        }
    }

    public static CloseableHttpResponse doGet(String url) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpGet);
        assert closeableHttpResponse != null;
        return closeableHttpResponse;
    }

    public static void doPost(String url, String jsonRespVOList) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        JSONObject jsonObject = new JSONObject();
        MapUtils.putAll(jsonObject, new String[] {"topic", topic, "token", token, "content", jsonRespVOList, "template", "json", "callbackUrl", ""});
        StringEntity entity = new StringEntity(jsonObject.toString(), "UTF-8");
        httpPost.setEntity(entity);
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        assert httpResponse != null;
        httpResponse.close();
    }

}
